import axios from 'axios'
// import {Message, MessageBox} from 'element-ui'
import {Toast} from 'vant'
// import store from '../store'
import jwt from 'jsonwebtoken'
import {getUrlParams} from '@/utils'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 50000 // 请求超时时间
})
const token = getUrlParams(window.location.href).stoken;
const sign = getUrlParams(window.location.href).sign;

if (token) {
  localStorage.setItem('token', token)
}
if (sign) {
  localStorage.setItem('sign', sign)
}

const commonHeader = {
  'x-api-version': 'v1',
  'x-sign': localStorage.getItem('sign'),
  'x-client': 'PC', //	请求客户端	String	2	Y	PC：PC浏览器，APP：移动客户端，H5：H5客户端，WX：微信客户端，MP：小程序客户端
  'x-token': localStorage.getItem('token')	 //	用户认证会话Token
};

function jsonwebtoken(config) {
  const privateKey = 'BoK0lYRnRZaS9TdHlZRVJNM29iWWlOTzdVZFVKCnJLUDJHbGtENmtTMEhUQ3p6V0FoYlJxZm';
  const postData = {
    ...config.data
    // timestamp: moment().valueOf()
  };
  const key = jwt.sign(postData, privateKey);
  return {key};
}

service.interceptors.request.use(config => {
  if ((!(getUrlParams(window.location.href).debug && process.env.NODE_ENV !== 'production'))) {
    config.data = process.env.JWT ? jsonwebtoken(config) : config.data;
  }
  // if (store.getters.token) {
  //   config.headers['boss-map'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  // }
  config.headers = {
    ...config.headers,
    ...commonHeader
  }// 让每个请求携带自定义token 请根据实际情况自行修改
  return config;
}, err => {
  Toast({
    icon: 'warning-o',
    message: '请求超时',
    duration: 5 * 1000
  });
  return Promise.resolve(err);
})

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.status !== 'success') {
      Toast({
        icon: 'warning-o',
        message: res.message,
        duration: 5 * 1000
      });
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  error => {
    console.log('err' + error)// for debug
    Toast({
      icon: 'warning-o',
      message: error.message,
      duration: 5 * 1000
    });
    return Promise.reject(error)
  }
)

export default service
